package com.py.custom.business.demo.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.py.custom.business.demo.core.mapstruct.BeanConvertUtils;
import com.py.custom.business.demo.core.service.MessageReachService;
import com.py.custom.business.demo.core.utils.MessageProcessUtils;
import com.py.custom.business.demo.feign.gateway.MessageSendGateway;
import com.py.custom.business.demo.protocol.constants.Constants;
import com.py.custom.business.demo.protocol.dto.MessageTaskDTO;
import com.py.custom.business.demo.protocol.dto.SendResultDTO;
import com.py.custom.business.demo.protocol.request.MessageRequest;
import com.py.custom.common.web.exception.BizException;
import com.py.custom.data.entity.demo.Record;
import com.py.custom.data.entity.demo.Template;
import com.py.custom.data.mapper.demo.RecordDao;
import com.py.custom.data.mapper.demo.TemplateDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * description：
 */
@Service
@Slf4j
public class MessageReachServiceImpl implements MessageReachService {

    @Resource
    private TemplateDao templateDao;

    @Resource
    private RecordDao recordDao;

    @Resource
    private MessageSendGateway messageSendGateway;

    @Autowired
    private BeanConvertUtils beanConvertUtils;

    /**
     * 发送
     *
     * @param request
     * @return
     */
    @Override
    public Boolean send(MessageRequest request) {
        Template template = templateDao.selectById(request.getTemplateId());
        if (Objects.isNull(template)) {
            throw new BizException("查询结果为空，请检查模板id：" + request.getTemplateId());
        }
        Integer templateType = template.getTemplateType();
        if (0 == templateType) {
            // 普通消息，直接发送
            return true;
        }
        // 处理成最终消息
        String content = MessageProcessUtils.process(template.getVariableValue(), template.getTemplateContent(),
                request.getVariableMap());
        log.info("发送的消息是：{}", content);

        // 1.转换成消息任务类
        MessageTaskDTO messageTaskDto = beanConvertUtils.message2Dto(content, request);

        // 2.记录消息发送
        Record record = beanConvertUtils.template2Record(request, 0, content, null);
        recordDao.insert(record);

        // 3.发送消息
        SendResultDTO resultDto = messageSendGateway.send(messageTaskDto);

        // 4.更新状态
        Integer status = MessageProcessUtils.processStatus(resultDto.getCode());
        LambdaUpdateWrapper<Record> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Record::getRecordId, record.getRecordId()).eq(Record::getStatus, 0)
                .set(Objects.nonNull(resultDto.getMsg()), Record::getFailMsg, resultDto.getMsg())
                .set(Objects.nonNull(status), Record::getStatus, status)
                .set(Record::getUpdateTime,
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
        recordDao.update(null, updateWrapper);
        return true;
    }
}
